package model;

import constant.Msg;
import util.AppUtil;
import util.RecipeUtil;

import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
public class Recipe extends Model<Recipe> {
	private static final long serialVersionUID = 1L;
	public static final Recipe dao = new Recipe();
	public static final String getCountSql = "select count(*) as num from recipes where 1=1;";/* 数据交互 *//* select */
	public static final String selectPageSql = "select * from recipes where type=? limit ?,?";
	public static final String selectSql = "select * from recipes where type=?";
	public static final String searchSql = "select * from recipes where title like ";
	public String selectById(Integer id) {
		try {
			Recipe recipe = Recipe.dao.findById(id);
			return AppUtil.modelToJson(recipe);
		} catch (Exception e) {
			e.printStackTrace();
			return Msg.ERROR_UNKNOWN;
		}
	}
	
	/* insert */
	public String add(Recipe recipe) {
		try {
			recipe.save();
			return Msg.SUCCESS_EXECUTE;
		} catch (Exception e) {
			e.printStackTrace();
			return Msg.ERROR_UNKNOWN;
		}
	}
	
	/* delete */
	public String delete(Integer id) {
		try {
			Recipe.dao.deleteById(id);
			return Msg.SUCCESS_EXECUTE;
		} catch (Exception e) {
			e.printStackTrace();
			return Msg.ERROR_UNKNOWN;
		}
	}
	
	/* update */
	public String update(Recipe recipe) {
		try {
			StringBuffer updateSql = new StringBuffer("update recipes set ");
			Map<String, String> attrMap = AppUtil.getAttr(recipe);
			for (Map.Entry<String, String> entry : attrMap.entrySet()) {
				updateSql.append(entry.getKey() + "=");
				if (!AppUtil.isNum(entry.getValue())) {
					updateSql.append("\"" + entry.getValue() + "\"");
				} else {
					updateSql.append(entry.getValue());
				}
				updateSql.append(",");
			}
			updateSql.deleteCharAt(updateSql.length() - 1);
			updateSql.append(" where id=" + recipe.getStr("id"));
			System.out.println(updateSql.toString());
			Db.update(updateSql.toString());
			return Msg.SUCCESS_EXECUTE;
		} catch (Exception e) {
			e.printStackTrace();
			return Msg.ERROR_UNKNOWN;
		}
	}

	/*
	 * select    *     from table where type=? (limit ?,?);
	 *        count(*)                  title=?%
	 *                                  technology=?
	 *                                  rate=?
	 *                                  foods=?%
	 *                                  region_taste=?%
	 *                                  
	 *                                  
	 */
	public String select(String type, String title, String technology,String rate,
			String foods, String region_taste,String offset, String length, String order) {
		try {
			List<Recipe> recipes = Recipe.dao.find(recipeSelectSql(
					false, type, title, technology, rate, foods,
						region_taste, offset, length, order));
			
			if(offset!=null && length!=null){
				int count = Recipe.dao.find(recipeSelectSql(
						true, type, title, technology, rate, foods,
							region_taste, null, null, null)).get(0).getInt("num");
				int countPerPage = Integer.parseInt(length);
				int page = count==0?0:(count%countPerPage==0?count/countPerPage:(count/countPerPage)+1);
				return AppUtil.modelToJson(recipes, page);
			}else{
				return AppUtil.modelToJson(recipes);
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
			return Msg.ERROR_UNKNOWN;
		}
	}

	public String random(Integer length) {
		try {/* 需要自己写逻辑代码 */
			return Msg.SUCCESS_EXECUTE;
		} catch (Exception e) {
			e.printStackTrace();
			return Msg.ERROR_UNKNOWN;
		}
	}

	public String search(String keyword) {
		try {
			System.out.println(searchSql+" '%"+keyword+"%';");
			List<Recipe> recipes = Recipe.dao.find(searchSql+" '%"+keyword+"%';");
			return AppUtil.modelToJson(recipes);
		} catch (Exception e) {
			e.printStackTrace();
			return Msg.ERROR_UNKNOWN;
		}
	}
	
	public String getFilter(String filter){
		try{
			String sql = "select distinct "+filter+" from recipes where 1=1";
			StringBuffer result = new StringBuffer();
			result.append("{\"code\": 0,\"msg\": \"成功\",\"data\": [");
			List<Record> recordList = Db.find(sql);
			for (Record record : recordList) {
				if(record.getStr(filter)!=null){
					result.append("\""+record.getStr(filter)+"\"");
					if(record!=recordList.get(recordList.size()-1)){
						result.append(",");
					}
				}
			}
			result.append("]}");
			return result.toString();
		}catch(Exception e){
			e.printStackTrace();
			return Msg.ERROR_UNKNOWN;
		}
	}
	
	
	public String detail(Integer id){
		return RecipeUtil.recipeDetail(id);
	}
	
	public String shicai(String keyword){
		return RecipeUtil.shicaiSearch(keyword);
	}
	
	public String cook(String foodsname){
		return RecipeUtil.smartCook(foodsname, null, null, null);
	}
	
	/* 工具部分 *//* 获取总条数 */

	public int getCount() {
		int num = 0;
		num = Db.find(getCountSql).get(0).getInt("num");
		return num;
	}

	public int getPage(Integer length) {
		int num = getCount();
		if (num == 0)
			return 0;
		return num % length == 0 ? num / length : (num / length) + 1;
	}/* 验证函数 *//* 偏移量超出检测 */

	public boolean checkOffsetOut(Integer offset) {
		if (offset >= getCount())
			return false;
		else
			return true;
	}
	
	
	
	/*
	 * select    *     from table where type=? (limit ?,?);
	 *        count(*)                  title=?%
	 *                                  technology=?
	 *                                  rate=?
	 *                                  foods=?%
	 *                                  region_taste=?%
	 *                                  
	 *                                  
	 */
	private String recipeSelectSql(boolean count, String type, String title, String technology,
			String rate, String foods, String region_taste,String offset, String length, String order){
		StringBuffer sb = new StringBuffer();
		sb.append("select ");
		if(count){
			sb.append(" count(*) as num");
		}else sb.append(" * ");
		
		sb.append(" from recipes where ");
		if(type!=null) sb.append(" type like '%"+type+"%' and");
		if(title!=null)	sb.append(" title like '%"+title+"%' and");
		if(technology!=null) sb.append(" technology like '%"+technology+"%' and");
		if(rate!=null) sb.append(" rate="+rate+" and");
		if(foods!=null) sb.append(" foods like '%"+foods+"%' and");
		if(region_taste!=null && !"味".equals(region_taste)) sb.append(" region_taste like '%"+region_taste+"%'");
		
		System.out.println(sb.substring(sb.length()-3));
		if("and".equals(sb.substring(sb.length()-3))){
			sb.delete(sb.length()-3, sb.length());
		}
		
		if(order!=null && ("did_num".equals(order) || "rate".equals(order)))
			sb.append(" order by "+rate+" DESC ");
		
		if(offset!=null){
			sb.append(" limit "+offset+",");
		}else{
			sb.append(" limit 0,");
		}
		
		if(length!=null){
			if(Integer.parseInt(length)<=30) sb.append(length);
			else sb.append("30");
		}else{
			sb.append("10");
		}
		
		sb.append(";");
		return sb.toString();
	}
}
